import axios, {
  InternalAxiosRequestConfig,
  AxiosResponse,
  AxiosPromise,
} from "axios";
import { useUserStore } from "@/store/modules/user";
import router from "@/router";
// 引入qs模块，对数据进行序列化
// import QS from "qs";
import nProgress from "nprogress";
import "nprogress/nprogress.css";

const baseURL = import.meta.env.VITE_APP_BASE_API;

// 创建 axios 实例
export const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  // headers: { "Content-Type": "application/json;charset=utf-8" },
});
// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    nProgress.start();
    const userStore = useUserStore();
    config.headers["Token"] =
      userStore.pinia_token || localStorage.getItem("pinia_token");
    if (config.method?.toUpperCase() === "POST") {
      config.headers["Content-Type"] = config["Content-Type"];
    } else if (config.method?.toUpperCase() === "GET") {
      config.data = true; //设置data使get方法设置请求头生效
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const userStore = useUserStore();
    nProgress.done();
    const { code, msg } = response.data;
    if (code == 403) {
      ElMessage.error("重新登录");
      router.replace({ path: "/login" });
      userStore.setToken("");
    } else if (response.status === 200) {
      return response;
    } else {
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    }
  },
  (error: any) => {
    if (error.response) {
      const userStore = useUserStore();
      let { status } = error.response;
      // token 过期,重新登录
      switch (status) {
        case 400:
          ElMessage.error("错误请求(400)");
          break;
        case 401:
          ElMessage.error("未授权,请重新登录(401)");
          userStore.logout();
          break;
        case 403:
          ElMessage.error("拒绝访问(403)");
          console.log(status, "dkjfdjkfj");
          userStore.logout();
          break;
        case 404:
          ElMessage.error("请求错误,未找到该资源(404)");
          break;
        case 405:
          ElMessage.error("错误请求(405)");
          break;
        case 408:
          ElMessage.error("请求超时(408)");
          break;
        case 500:
          ElMessage.error("服务器错误(500)");
          break;
        case 501:
          ElMessage.error("服务未实现(501)");
          break;
        case 502:
          ElMessage.error("网络错误(502)");
          break;
        case 503:
          ElMessage.error("服务不可用(503)");
          break;
        case 504:
          ElMessage.error("网络超时(504)");
          break;
        case 505:
          ElMessage.error("HTTP版本不受支持(505)");
          break;
        default:
          ElMessage.error("网络出现问题,请稍后再试");
          break;
      }
    }
    return Promise.reject(error.message);
  }
);

type Data<T> = {
  code: number;
  msg: string;
  data: T;
};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function getApi(url: string, params: object): AxiosPromise<any> {
  return new Promise((resolve, reject) => {
    const fullUrl = `${baseURL}${url}`;
    service
      .get(fullUrl, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} option [额外配置请求头等]
 */
export function postApi(
  url: string,
  params: object,
  option: object = { "Content-Type": "application/json" }
): AxiosPromise<any> {
  return new Promise((resolve, reject) => {
    const fullUrl = `${baseURL}${url}`;
    service
      .post(fullUrl, params, option)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
